import {AxiosRequest} from "@kordar-lib/request";
import {Admin as user, App as app} from "@kordar-lib/reducers";
import {environment} from "../common/environment";
import RespCode from "../common/resp";
import {$notice} from "@kordar/easyui";

export const config = {
    timeout: 30000,
    baseURL: environment.API_HOST
}

const beforeRequest = (cfg) => {
    let headers = cfg.headers;
    // 设置语言
    headers.Locale = app.locale();
    // 设置用户Token
    if (!user.isGuest()) {
        headers.Token = user.token();
    }
    return cfg
}




const beforeResponse = (response) => {

    if (response.data.type === "application/octet-stream") {
        return response;
    }

    let {code, message, data} = response.data
    if (code === RespCode.unauthorized) {
        $notice.error(message||"no access permission!")
        logout(code, message, data)
    } else if (code === RespCode.validate || code === RespCode.validate2) {
        $notice.validate(Object.values(data), "", 8000)
    } else if (code !== RespCode.success) {
        $notice.error(message)
        // logout(code, message, data)
    }

    return response.data
}

const error = (err) => {
    console.log(err)
}

// @ts-ignore
const logout = (code, message, data) => {

    if (user.isGuest()) {
        user.clear()
    }

    user.logout(() => {
        window.location.href = '/login'
    })
}

export const request = new AxiosRequest(config, beforeRequest, beforeResponse, error)
